package com.coffee.sku.service.sku.impl;

import com.alibaba.fastjson.JSONObject;
import com.coffee.admin.api.common.query.GtRegionQuery;
import com.coffee.admin.api.platform.query.PlatformSystemDeployQuery;
import com.coffee.admin.service.common.bean.GtRegion;
import com.coffee.admin.service.common.dao.GtRegionDao;
import com.coffee.admin.service.merchant.bean.Merchant;
import com.coffee.admin.service.merchant.dao.MerchantDao;
import com.coffee.admin.service.platform.bean.PlatformBaseDeploy;
import com.coffee.admin.service.platform.bean.PlatformSystemDeploy;
import com.coffee.admin.service.platform.dao.PlatformBaseDeployDao;
import com.coffee.admin.service.platform.dao.PlatformSystemDeployDao;
import com.coffee.admin.service.supplier.bean.Supplier;
import com.coffee.admin.service.supplier.bean.SupplierBaseDeploy;
import com.coffee.admin.service.supplier.dao.SupplierBaseDeployDao;
import com.coffee.admin.service.supplier.dao.SupplierDao;
import com.coffee.core.entity.Page;
import com.coffee.core.entity.PagerInfo;
import com.coffee.core.enums.ExceptionEnum;
import com.coffee.core.enums.IntegralOperationEnum;
import com.coffee.core.enums.SkuSalesInformationTypeEnum;
import com.coffee.core.enums.SkuTypeEnum;
import com.coffee.core.exception.BusinessException;
import com.coffee.core.exception.ValidateBusinessException;
import com.coffee.core.util.BeanUtilExt;
import com.coffee.core.util.BeanUtils;
import com.coffee.core.util.DTOUtils;
import com.coffee.core.util.StringUtil;
import com.coffee.order.api.sku.query.UrbanFullReductionQuery;
import com.coffee.order.api.sku.result.MerchantSpellOrderResult;
import com.coffee.order.api.sku.result.PeriodizationSkuResult;
import com.coffee.order.api.sku.service.SkuOrderService;
import com.coffee.order.service.inquire.bean.InquireOrderPlan;
import com.coffee.order.service.sku.bean.EnjoyBeforePaySku;
import com.coffee.order.service.sku.bean.UrbanFullReduction;
import com.coffee.order.service.sku.dao.EnjoyBeforePaySkuDao;
import com.coffee.order.service.sku.dao.PeriodizationSkuDao;
import com.coffee.order.service.sku.dao.UrbanFullReductionDao;
import com.coffee.sku.api.sku.query.RegionalSkuSalesInformationQuery;
import com.coffee.sku.api.sku.query.SkuContentQuery;
import com.coffee.sku.api.sku.query.SkuSalesInformationQuery;
import com.coffee.sku.api.sku.req.*;
import com.coffee.sku.api.sku.result.*;
import com.coffee.sku.api.sku.service.SkuContentService;
import com.coffee.sku.service.sku.bean.*;
import com.coffee.sku.service.sku.dao.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@DubboService(dynamic = true)
public class SkuContentServiceImpl implements SkuContentService {
    private final static Logger logger = LoggerFactory.getLogger(SkuContentServiceImpl.class);
    @Value("${cityId}")
    private String nationwideId;
    @Resource
    private SkuContentDao skuContentDao;
    @Resource
    private SkuCategoryDao skuCategoryDao;
    @Resource
    private SkuSalesInformationDao skuSalesInformationDao;
    @Resource
    private RegionalSkuSalesInformationDao regionalSkuSalesInformationDao;
    @Resource
    private RegionalSkuDao regionalSkuDao;
    @Resource
    private PlatformBaseDeployDao platformBaseDeployDao;
    @Resource
    private SkuDao skuDao;
    @Resource
    private GtRegionDao gtRegionDao;
    @Resource
    private PlatformSystemDeployDao platformSystemDeployDao;
    @Resource
    private MerchantDao merchantDao;
    @Resource
    private SupplierDao supplierDao;
    @Resource
    private UrbanFullReductionDao urbanFullReductionDao;
    @Resource
    private EnjoyBeforePaySkuDao enjoyBeforePaySkuDao;
    @Resource
    private PeriodizationSkuDao periodizationSkuDao;
    @DubboReference
    private SkuOrderService skuOrderService;


    @Override
    public Page<SkuContentResult> getPager(SkuContentQuery param, PagerInfo pr) {
        Page<SkuContentResult> pager = new Page<SkuContentResult>(pr.getStart(), pr.getPageSize());
        Integer count = skuContentDao.count(param);
        pager.setTotalPage(count);
        if (count > 0) {
            List<SkuContent> list = skuContentDao.page(param, pr.getStart(), pr.getPageSize());
            pager.setData(DTOUtils.convertList(list, SkuContentResult.class));
        }
        return pager;
    }

    @Override
    public Page<SkuListResult> findList(SkuListReq param, PagerInfo pr) {
        Page<SkuListResult> skuListResultPage = new Page<SkuListResult>(pr.getStart(), pr.getPageSize());
        Integer i = Integer.parseInt(nationwideId);
        if (param.getCityId() == null || i.equals(param.getCityId())) {
            skuListResultPage = findListNoCity(param, pr);
        } else {
            skuListResultPage = findListByCity(param, pr);
        }
        return skuListResultPage;
    }

    public Page<SkuListResult> findListNoCity(SkuListReq param, PagerInfo pr) {
        Page<SkuListResult> pager = new Page<SkuListResult>(pr.getStart(), pr.getPageSize());
        Integer count = skuContentDao.skuCount(param);
        pager.setTotalPage(count);
        if (count > 0) {
            List<RegionalSku> skuListResults = regionalSkuDao.listAll();
            Map<Integer, RegionalSku> regionalSkuMap = skuListResults.stream().collect(Collectors.toMap(RegionalSku::getSkuId, i -> i));
            List<SkuListResult> skuListReps = skuContentDao.skuPage(param, pr.getStart(), pr.getPageSize());
            for (SkuListResult skuListRep : skuListReps) {
                if (StringUtils.isNotEmpty(skuListRep.getPidPath())) {
                    String[] split = skuListRep.getPidPath().split(",");
                    SkuCategory skuCategory = skuCategoryDao.findById(Integer.parseInt(split[0]));
                    if (skuCategory != null) {
                        skuListRep.setCategoryName(skuCategory.getName());
                    }
                    RegionalSku regionalSku = regionalSkuMap.get(skuListRep.getSkuId());
                    if (regionalSku!=null){
                        skuListRep.setIsMembersExclusive(regionalSku.getIsMembersExclusive());
                    }
                }
                SkuSalesInformationQuery skuSalesInformationQuery = new SkuSalesInformationQuery();
                skuSalesInformationQuery.setSkuId(skuListRep.getSkuId());
                skuSalesInformationQuery.setType(param.getType());
                List<SkuSalesInformation> skuSalesInformations = skuSalesInformationDao.list(skuSalesInformationQuery);
                List<SkuSalesInformationResult> skuSalesInformationResults = DTOUtils.convertList(skuSalesInformations, SkuSalesInformationResult.class);
                for (SkuSalesInformationResult skuSalesInformationResult : skuSalesInformationResults) {
                    if (skuSalesInformationResult.getIntegralDeduction() == null) {
                        skuSalesInformationResult.setIntegralDeduction(skuListRep.getIntegralDeduction());
                    }
                }
                skuListRep.setSkuSalesInformationResults(skuSalesInformationResults);
            }
            pager.setData(skuListReps);
        }
        return pager;
    }


    public Page<SkuListResult> findListByCity(SkuListReq param, PagerInfo pr) {
        Page<SkuListResult> pager = new Page<SkuListResult>(pr.getStart(), pr.getPageSize());
        Integer skuIdsCount = regionalSkuSalesInformationDao.skuCount(param);
        pager.setTotalPage(skuIdsCount);
        if (skuIdsCount > 0) {
            List<RegionalSku> skuListResults = regionalSkuDao.listAll();
            Map<Integer, RegionalSku> regionalSkuMap = skuListResults.stream().collect(Collectors.toMap(RegionalSku::getSkuId, i -> i));
            List<Integer> skuIdsByPage = regionalSkuSalesInformationDao.getSkuIdsByReq(param, pr.getStart(), pr.getPageSize());
            List<SkuListResult> skuListReps = skuContentDao.skuPageById(skuIdsByPage);
            for (SkuListResult skuListRep : skuListReps) {
                if (StringUtils.isNotEmpty(skuListRep.getPidPath())) {
                    String[] split = skuListRep.getPidPath().split(",");
                    SkuCategory skuCategory = skuCategoryDao.findById(Integer.parseInt(split[0]));
                    if (skuCategory != null) {
                        skuListRep.setCategoryName(skuCategory.getName());
                    }
                }
                RegionalSku regionalSku = regionalSkuMap.get(skuListRep.getSkuId());
                if (regionalSku!=null){
                    skuListRep.setIsMembersExclusive(regionalSku.getIsMembersExclusive());
                }
                SkuSalesInformationQuery skuSalesInformationQuery = new SkuSalesInformationQuery();
                skuSalesInformationQuery.setSkuId(skuListRep.getSkuId());
                List<SkuSalesInformation> skuSalesInformations = skuSalesInformationDao.list(skuSalesInformationQuery);
                List<SkuSalesInformationResult> skuSalesInformationResults = DTOUtils.convertList(skuSalesInformations, SkuSalesInformationResult.class);
                for (SkuSalesInformationResult skuSalesInformationResult : skuSalesInformationResults) {
                    if (skuSalesInformationResult.getIntegralDeduction() == null) {
                        skuSalesInformationResult.setIntegralDeduction(skuListRep.getIntegralDeduction());
                    }
                }
                skuListRep.setSkuSalesInformationResults(skuSalesInformationResults);
            }
            pager.setData(skuListReps);
        }
        return pager;
    }


    @Override
    public Page<MerchantSkuListResult> findMerchantSkuList(MerchantSkuListReq param, PagerInfo pr) {
        Page<MerchantSkuListResult> merchantSkuList = new Page<>(pr.getPageIndex(), pr.getPageSize());
        if (param.getCityId() == null) {
            if (!SkuSalesInformationTypeEnum.PERIODIZATION.getCode().equals(param.getType())) {
                merchantSkuList = findMerchantSkuListNoCity(param, pr);
            }
        } else {
            Integer skuIdsCount = regionalSkuSalesInformationDao.getSkuIdsCount(param);
            if (skuIdsCount > 0) {
                merchantSkuList = findMerchantSkuListByCity(param, pr);
            } else {
                if (!SkuSalesInformationTypeEnum.PERIODIZATION.getCode().equals(param.getType())) {
                    merchantSkuList = findMerchantSkuListNoCity(param, pr);
                }
            }
        }
        return merchantSkuList;
    }

    public Page<MerchantSkuListResult> findMerchantSkuListNoCity(MerchantSkuListReq param, PagerInfo pr) {
        Page<MerchantSkuListResult> pager = new Page<MerchantSkuListResult>(pr.getStart(), pr.getPageSize());
        Integer count = skuContentDao.merchantSkuCount(param);
        pager.setTotalPage(count);
        if (count > 0) {
            List<MerchantSkuListResult> merchantSkuListReps = skuContentDao.merchantSkuPage(param, pr.getStart(), pr.getPageSize());
            List<RegionalSku> skuListResults = regionalSkuDao.listAll();
            Map<Integer, RegionalSku> regionalSkuMap = skuListResults.stream().collect(Collectors.toMap(RegionalSku::getSkuId, i -> i));
            List<RegionalSkuSalesInformation> list = regionalSkuSalesInformationDao.list(new RegionalSkuSalesInformationQuery());
            Map<String, RegionalSkuSalesInformation>  regionalSkuSalesInformationMap= list.stream().collect(Collectors.toMap(r -> r.getSkuId() + "_" + r.getGtRegionId(), i -> i, (value1, value2) -> value2));
            for (MerchantSkuListResult merchantSkuListRep : merchantSkuListReps) {
                if (param.getCityId() != null) {
                    RegionalSku regionalSku = regionalSkuMap.get(merchantSkuListRep.getId());
                    if (regionalSku!=null){
                        merchantSkuListRep.setIsMembersExclusive(regionalSku.getIsMembersExclusive());
                    }
                    RegionalSkuSalesInformation regionalSkuSalesInformation = regionalSkuSalesInformationMap.get(merchantSkuListRep.getId() + "_" + param.getCityId());
                    if (regionalSkuSalesInformation != null) {
                        merchantSkuListRep.setPrice(regionalSkuSalesInformation.getRegionalPrice());
                    }
                }
                if (merchantSkuListRep.getSpellOrderCityId() != null) {
                    GtRegion gtRegion = gtRegionDao.findById(merchantSkuListRep.getSpellOrderCityId());
                    merchantSkuListRep.setSpellOrderCity(gtRegion.getName());
                }
                if ("Y".equals(merchantSkuListRep.getIsSpellOrder())) {
                    SkuSalesInformation salesInformation = skuSalesInformationDao.findById(merchantSkuListRep.getSkuSalesInformationId());
                    merchantSkuListRep.setPrice(salesInformation.getSpellOrderPrice());
                }
                EnjoyBeforePaySku enjoyBeforePaySku = enjoyBeforePaySkuDao.findBySkuId(merchantSkuListRep.getId());
                if (enjoyBeforePaySku != null) {
                    merchantSkuListRep.setIsEnjoy("Y");
                }
            }
            pager.setData(merchantSkuListReps);
        }
        return pager;
    }

    public Page<MerchantSkuListResult> findMerchantSkuListByCity(MerchantSkuListReq param, PagerInfo pr) {
        Page<MerchantSkuListResult> pager = new Page<MerchantSkuListResult>(pr.getStart(), pr.getPageSize());
        logger.info("param======" + JSONObject.toJSONString(param));
        List<RegionalSkuIdAndPriceResult> regionalSkuIdAndPriceResults = regionalSkuSalesInformationDao.getSkuIds(param, pr.getStart(), pr.getPageSize());
        logger.info("regionalSkuIdAndPriceResults====" + JSONObject.toJSONString(regionalSkuIdAndPriceResults));
        if (regionalSkuIdAndPriceResults.size() > 0) {
            List<Integer> skuIds = regionalSkuIdAndPriceResults.stream().map(r -> r.getId()).collect(Collectors.toList());
            List<MerchantSkuListResult> merchantSkuListReps = skuContentDao.merchantSkuPageBySkuIds(skuIds);
            List<RegionalSku> skuListResults = regionalSkuDao.listAll();
            Map<Integer, RegionalSku> regionalSkuMap = skuListResults.stream().collect(Collectors.toMap(RegionalSku::getSkuId, i -> i));
            List<RegionalSkuSalesInformation> list = regionalSkuSalesInformationDao.list(new RegionalSkuSalesInformationQuery());
            Map<String, RegionalSkuSalesInformation> regionalSkuSalesInformationMap = list.stream().collect(Collectors.toMap(r -> r.getSkuId() + "_" + r.getGtRegionId(), i -> i, (value1, value2) -> value2));
            List<GtRegion> gtRegions = gtRegionDao.list(new GtRegionQuery());
            Map<Integer, GtRegion> gtRegionMap = gtRegions.stream().collect(Collectors.toMap(r -> r.getId(), i -> i));
            SkuSalesInformationQuery skuSalesInformationQuery = new SkuSalesInformationQuery();
            skuSalesInformationQuery.setIsDelete("N");
            List<SkuSalesInformation> skuSalesInformations = skuSalesInformationDao.list(skuSalesInformationQuery);
            Map<Integer, SkuSalesInformation> integerSkuSalesInformationMap = skuSalesInformations.stream().collect(Collectors.toMap(r -> r.getId(), i -> i));
            List<Integer> listSkuId = enjoyBeforePaySkuDao.listSkuId();
            for (MerchantSkuListResult merchantSkuListRep : merchantSkuListReps) {
                if (param.getCityId() != null) {
                    RegionalSku regionalSku = regionalSkuMap.get(merchantSkuListRep.getId());
                    if (regionalSku!=null){
                        merchantSkuListRep.setIsMembersExclusive(regionalSku.getIsMembersExclusive());
                    }
                    RegionalSkuSalesInformation regionalSkuSalesInformation = regionalSkuSalesInformationMap.get(merchantSkuListRep.getId() + "_" + param.getCityId());
                    if (regionalSkuSalesInformation != null) {
                        merchantSkuListRep.setSkuSalesInformationId(regionalSkuSalesInformation.getSkuSalesInformationId());
                        merchantSkuListRep.setPrice(regionalSkuSalesInformation.getRegionalPrice());
                    }
                }
                if (merchantSkuListRep.getSpellOrderCityId() != null) {
                    GtRegion gtRegion = gtRegionMap.get(merchantSkuListRep.getSpellOrderCityId());
                    merchantSkuListRep.setSpellOrderCity(gtRegion.getName());
                }
                if ("Y".equals(merchantSkuListRep.getIsSpellOrder())) {
                    SkuSalesInformation salesInformation = integerSkuSalesInformationMap.get(merchantSkuListRep.getSkuSalesInformationId());
                    merchantSkuListRep.setPrice(salesInformation.getSpellOrderPrice());
                }
                boolean contains = listSkuId.contains(merchantSkuListRep.getId());
                if (contains) {
                    merchantSkuListRep.setIsEnjoy("Y");
                }
            }
            long t13 = System.currentTimeMillis();
            if (StringUtils.isNotBlank(param.getPriceAscending())) {
                merchantSkuListReps = merchantSkuListReps.stream().sorted(Comparator.comparing(MerchantSkuListResult::getPrice)).collect(Collectors.toList());
            } else if (StringUtils.isNotBlank(param.getPriceDescending())) {
                merchantSkuListReps = merchantSkuListReps.stream().sorted(Comparator.comparing(MerchantSkuListResult::getPrice).reversed()).collect(Collectors.toList());
            }
            pager.setData(merchantSkuListReps);
        }
        return pager;
    }


    @Override
    public Integer count(SkuContentQuery param) {
        Integer count = skuContentDao.count(param);
        return count;
    }

    @Override
    public SkuContentResult getDetail(Integer id) throws BusinessException {
        SkuContentResult skuContentResult = skuContentDao.findSkuContentResultBySkuId(id);
        if (skuContentResult == null) {
            throw new BusinessException(ExceptionEnum.ERROR_1318.getCode(), ExceptionEnum.ERROR_1318.getMessage());
        }
        ValidateBusinessException.assertTrue(SkuTypeEnum.SKU.getCode().equals(skuContentResult.getSkuType()), ExceptionEnum.ERROR_1318);
        SkuSalesInformationQuery skuSalesInformationQuery = new SkuSalesInformationQuery();
        skuSalesInformationQuery.setSkuId(skuContentResult.getSkuId());
        skuSalesInformationQuery.setIsDelete("N");
        skuSalesInformationQuery.setType(SkuSalesInformationTypeEnum.GENERAL.getCode());
        List<SkuSalesInformation> skuSalesInformations = skuSalesInformationDao.list(skuSalesInformationQuery);
        skuContentResult.setSkuSalesInformationResults(DTOUtils.convertList(skuSalesInformations, SkuSalesInformationResult.class));
        String categoryName = "";
        String pidPath = skuContentResult.getPidPath();
        List<Integer> categoryIds = new ArrayList<>();
        List<String> categoryNames = new ArrayList<>();
        if (StringUtils.isNotEmpty(pidPath)) {
            String[] split = pidPath.split(",");
            for (String s : split) {
                int i = Integer.parseInt(s);
                SkuCategory skuCategory = skuCategoryDao.findById(i);
                categoryIds.add(i);
                if (skuCategory != null) {
                    categoryNames.add(skuCategory.getName());
                    categoryName = skuCategory.getName() + "/";
                }
            }
        }
        skuContentResult.setCategoryIds(categoryIds);
        skuContentResult.setCategoryNames(categoryNames);
        if (skuContentResult.getSpellOrderCityId() != null) {
            GtRegion gtRegion = gtRegionDao.findById(skuContentResult.getSpellOrderCityId());
            skuContentResult.setSpellOrderCity(gtRegion.getName());
        }
        if (skuContentResult.getSupplierGoodsId() != null) {
            PlatformBaseDeploy platformBaseDeploy = platformBaseDeployDao.findById(skuContentResult.getSupplierGoodsId());
            if (platformBaseDeploy != null)
                skuContentResult.setSupplierGoodsName(platformBaseDeploy.getName());
        }

        skuContentResult.setCategoryName(categoryName);
        return skuContentResult;
    }

    @Override
    public List<SkuContentResult> getList(SkuContentQuery param, PagerInfo pr) {
        List<SkuContent> list = skuContentDao.page(param, pr.getStart(), pr.getPageSize());
        return DTOUtils.convertList(list, SkuContentResult.class);
    }

    @Override
    public List<SkuContentResult> getList(SkuContentQuery param) {
        List<SkuContent> list = skuContentDao.page(param, 0, Integer.MAX_VALUE);
        return DTOUtils.convertList(list, SkuContentResult.class);
    }

    @Override
    public List<SkuContentResult> getList() {
        SkuContentQuery param = new SkuContentQuery();
        List<SkuContent> list = skuContentDao.page(param, 0, Integer.MAX_VALUE);
        return DTOUtils.convertList(list, SkuContentResult.class);
    }


    @Override
    public void delete(Integer id) {
        Sku sku = new Sku();
        sku.setId(id);
        sku.setIsDelete("Y");
        sku.setSkuType(SkuTypeEnum.SKU.getCode());
        skuDao.updateById(sku);
    }

    @Override
    public void addOrUpdate(SkuContentResult result) throws BusinessException {
        SkuContent item = new SkuContent();
        BeanUtilExt.copyProperties(item, result);
        if (item.getId() == null) {
            item.setCreateTime(new Date());
            skuContentDao.insert(item);
        } else {
            SkuContent tmp = skuContentDao.findById(item.getId());
            if (tmp == null) {
                throw new BusinessException(ExceptionEnum.ERROR_0002.getCode(), ExceptionEnum.ERROR_0002.getMessage());
            }
            skuContentDao.updateById(item);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addSku(SkuAddReq skuAddReq) throws BusinessException {
        ValidateBusinessException.assertStringNotBlank(skuAddReq.getTitle(), ExceptionEnum.ERROR_1319);
        ValidateBusinessException.assertIdNotNull(skuAddReq.getSupplierId(), ExceptionEnum.ERROR_1321);
        ValidateBusinessException.assertIdNotNull(skuAddReq.getCategoryId(), ExceptionEnum.ERROR_1322);
        ValidateBusinessException.assertStringNotBlank(skuAddReq.getLogistics(), ExceptionEnum.ERROR_1323);
        ValidateBusinessException.assertStringNotBlank(skuAddReq.getCover(), ExceptionEnum.ERROR_1324);
        List<SkuSalesInformationReq> skuSalesInformationResults = skuAddReq.getSkuSalesInformationResults();
        ValidateBusinessException.assertCollectionNotEmpty(skuSalesInformationResults, ExceptionEnum.ERROR_1326);
        Sku sku = new Sku();
        sku.setTitle(skuAddReq.getTitle());
        sku.setSubTitle(skuAddReq.getSubtitle());
        sku.setSupplierId(skuAddReq.getSupplierId());
        sku.setCategoryId(skuAddReq.getCategoryId());
        sku.setIsEnable("N");
        sku.setCreateTime(new Date());
        sku.setIsDelete("N");
        sku.setSkuType(SkuTypeEnum.SKU.getCode());
        skuDao.insert(sku);
        SkuContent skuContent = new SkuContent();
        BeanUtils.copyProperties(skuContent, skuAddReq);
        skuContent.setSkuId(sku.getId());
        skuContent.setCreateTime(new Date());
        skuContent.setGoodsAttribute(JSONObject.toJSONString(skuAddReq.getGoodsAttribute()));
        skuContent.setOtherAttribute(JSONObject.toJSONString(skuAddReq.getOtherAttribute()));
        skuContentDao.insert(skuContent);
        insertSkuSalesInformation(skuSalesInformationResults, sku.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSku(SkuUpdateReq skuUpdateReq) throws BusinessException {
        Integer skuId = skuUpdateReq.getSkuId();
        ValidateBusinessException.assertIdNotNull(skuId, ExceptionEnum.ERROR_1327);
        ValidateBusinessException.assertStringNotBlank(skuUpdateReq.getTitle(), ExceptionEnum.ERROR_1319);
        ValidateBusinessException.assertIdNotNull(skuUpdateReq.getSupplierId(), ExceptionEnum.ERROR_1321);
        ValidateBusinessException.assertStringNotBlank(skuUpdateReq.getLogistics(), ExceptionEnum.ERROR_1323);
        ValidateBusinessException.assertStringNotBlank(skuUpdateReq.getCover(), ExceptionEnum.ERROR_1324);
        List<SkuSalesInformationReq> skuSalesInformationResults = skuUpdateReq.getSkuSalesInformationResults();
        ValidateBusinessException.assertCollectionNotEmpty(skuSalesInformationResults, ExceptionEnum.ERROR_1326);
        Sku sku = skuDao.findById(skuId);
        ValidateBusinessException.assertNonNull(sku, ExceptionEnum.ERROR_1318);
        ValidateBusinessException.assertFalse("Y".equals(sku.getIsEnable()), ExceptionEnum.ERROR_1334);
        String isApprove = sku.getIsApprove();
        sku = new Sku();
        sku.setId(skuId);
        sku.setSkuType(SkuTypeEnum.SKU.getCode());
        sku.setTitle(skuUpdateReq.getTitle());
        sku.setSubTitle(skuUpdateReq.getSubtitle());
        sku.setSupplierId(skuUpdateReq.getSupplierId());
        sku.setCategoryId(skuUpdateReq.getCategoryId());
        if ("N".equals(isApprove)) {
            sku.setIsApprove("W");
        }
        skuDao.updateById(sku);
        SkuContent skuContent = skuContentDao.findBySkuId(skuId);
        ValidateBusinessException.assertNonNull(skuContent, ExceptionEnum.ERROR_1318);
        SkuContent skuContentUpdate = new SkuContent();
        BeanUtils.copyProperties(skuContentUpdate, skuUpdateReq);
        skuContentUpdate.setId(skuContent.getId());
        skuContentUpdate.setGoodsAttribute(JSONObject.toJSONString(skuUpdateReq.getGoodsAttribute()));
        skuContentUpdate.setOtherAttribute(JSONObject.toJSONString(skuUpdateReq.getOtherAttribute()));
        skuContentDao.updateById(skuContentUpdate);
        //删除物流信息
        List<Integer> skuSalesInformationIds = skuSalesInformationDao.findSkuSalesInformationIdBySkuId(skuId);
        List<Integer> candidateTicketIds = skuSalesInformationResults.stream().filter(skuSalesInformationResult -> skuSalesInformationResult.getId() != null).map(SkuSalesInformationReq::getId).collect(Collectors.toList());
        Collection subtract = CollectionUtils.subtract(skuSalesInformationIds, candidateTicketIds);
        List<Integer> subtractList = new ArrayList<>(subtract);
        if (subtractList.size() > 0) {
            skuSalesInformationDao.deleteByIds(subtractList, SkuSalesInformationTypeEnum.GENERAL.getCode());
            regionalSkuSalesInformationDao.deleteBySkuSalesInformationIds(subtractList, SkuSalesInformationTypeEnum.GENERAL.getCode());
        }
        //添加新增的物流信息
        List<SkuSalesInformationReq> insertSkuSalesInformationList = skuSalesInformationResults.stream().filter(skuSalesInformationResult -> skuSalesInformationResult.getId() == null).collect(Collectors.toList());
        if (insertSkuSalesInformationList != null && insertSkuSalesInformationList.size() > 0) {
            insertSkuSalesInformation(insertSkuSalesInformationList, skuId);
        }
        //添加新增的物流信息
        List<SkuSalesInformationReq> updateSkuSalesInformationList = skuSalesInformationResults.stream().filter(skuSalesInformationResult -> skuSalesInformationResult.getId() != null).collect(Collectors.toList());
        if (updateSkuSalesInformationList != null && updateSkuSalesInformationList.size() > 0) {
            //修改物流信息
            updateSkuSalesInformation(updateSkuSalesInformationList, skuId);
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public void insertSkuSalesInformation(List<SkuSalesInformationReq> skuSalesInformationResults, Integer skuId) {
        for (SkuSalesInformationReq skuSalesInformationResult : skuSalesInformationResults) {
            SkuSalesInformation skuSalesInformation = new SkuSalesInformation();
            skuSalesInformation.setSkuId(skuId);
            skuSalesInformation.setProductName(skuSalesInformationResult.getProductName());
            skuSalesInformation.setPrice(skuSalesInformationResult.getPrice());
            skuSalesInformation.setSpellOrderPrice(skuSalesInformationResult.getSpellOrderPrice());
            skuSalesInformation.setSpecifications(skuSalesInformationResult.getSpecifications());
            skuSalesInformation.setStock(skuSalesInformationResult.getStock());
            skuSalesInformation.setIntegralDeduction(skuSalesInformationResult.getIntegralDeduction());
            skuSalesInformation.setIsDelete("N");
            skuSalesInformation.setCreateTime(new Date());
            skuSalesInformation.setCover(skuSalesInformationResult.getCover());
            skuSalesInformation.setUnit(skuSalesInformationResult.getUnit());
            skuSalesInformation.setType(SkuSalesInformationTypeEnum.GENERAL.getCode());
            skuSalesInformationDao.insert(skuSalesInformation);
        }
    }


    @Transactional(rollbackFor = Exception.class)
    public void updateSkuSalesInformation(List<SkuSalesInformationReq> skuSalesInformationResults, Integer skuId) {
        for (SkuSalesInformationReq skuSalesInformationResult : skuSalesInformationResults) {
            SkuSalesInformation skuSalesInformation = new SkuSalesInformation();
            skuSalesInformation.setId(skuSalesInformationResult.getId());
            skuSalesInformation.setSkuId(skuId);
            skuSalesInformation.setProductName(skuSalesInformationResult.getProductName());
            skuSalesInformation.setPrice(skuSalesInformationResult.getPrice());
            skuSalesInformation.setSpellOrderPrice(skuSalesInformationResult.getSpellOrderPrice());
            skuSalesInformation.setSpecifications(skuSalesInformationResult.getSpecifications());
            skuSalesInformation.setIntegralDeduction(skuSalesInformationResult.getIntegralDeduction());
            skuSalesInformation.setStock(skuSalesInformationResult.getStock());
            skuSalesInformation.setCover(skuSalesInformationResult.getCover());
            skuSalesInformation.setUnit(skuSalesInformationResult.getUnit());
            skuSalesInformationDao.updateById(skuSalesInformation);
        }
    }

    @Override
    public void updateIsEnable(Integer id, String isEnable, String skuType, Integer supplierId) throws BusinessException {
        Sku sku1 = skuDao.findById(id);
        ValidateBusinessException.assertTrue(sku1.getSupplierId().equals(supplierId), ExceptionEnum.ERROR_1342);
        Sku sku = new Sku();
        sku.setId(id);
        sku.setIsEnable(isEnable);
        sku.setSkuType(skuType);
        skuDao.updateById(sku);
    }

    @Override
    public void updateIsDisable(Integer id, String isDisable, String skuType) {
        Sku sku = new Sku();
        sku.setId(id);
        sku.setIsDisable(isDisable);
        sku.setSkuType(skuType);
        skuDao.updateById(sku);
    }

    @Override
    public void updateIsApprove(Integer id, String isApprove, String approveRefuseReason, String skuType) {
        Sku sku = new Sku();
        sku.setId(id);
        sku.setIsApprove(isApprove);
        sku.setSkuType(skuType);
        if ("N".equals(isApprove)) {
            sku.setApproveRefuseReason(approveRefuseReason);
            sku.setIsEnable("N");
        } else {
            sku.setIsEnable("Y");
        }
        skuDao.updateById(sku);
    }

    @Override
    public void updateSort(List<AddSkuSortReq> addSkuSortReq, Integer categoryId) {
        if (categoryId != null) {
            for (AddSkuSortReq skuSortReq : addSkuSortReq) {
                Sku sku = new Sku();
                sku.setId(skuSortReq.getSkuId());
                sku.setCategorySort(skuSortReq.getSort());
                skuDao.updateById(sku);
            }
        } else {
            for (AddSkuSortReq skuSortReq : addSkuSortReq) {
                Sku sku = new Sku();
                sku.setId(skuSortReq.getSkuId());
                sku.setSort(skuSortReq.getSort());
                skuDao.updateById(sku);
            }
        }
    }

    @Override
    public Map<Integer, SkuContentResult> getItemMap(Set<Integer> idSet) {
        Map<Integer, SkuContentResult> map = new HashMap<Integer, SkuContentResult>();
        List<SkuContent> list = skuContentDao.findByIds(StringUtil.setToList(idSet));
        List<SkuContentResult> resultList = DTOUtils.convertList(list, SkuContentResult.class);
        for (SkuContentResult item : resultList) {
            map.put(item.getId(), item);
        }
        return map;
    }

    @Override
    public Map<Integer, SkuContentResult> getItemMap() {
        Map<Integer, SkuContentResult> map = new HashMap<Integer, SkuContentResult>();
        SkuContentQuery param = new SkuContentQuery();
        List<SkuContent> list = skuContentDao.page(param, 0, Integer.MAX_VALUE);
        List<SkuContentResult> resultList = DTOUtils.convertList(list, SkuContentResult.class);
        for (SkuContentResult item : resultList) {
            map.put(item.getId(), item);
        }
        return map;
    }

    public static void main(String[] args) {
        String s = "{\\\"code\\\":200000,\\\"data\\\":{\\\"address\\\":\\\"浙江省杭州市建德市ui与i有\\\",\\\"expireTime\\\":1703235757000,\\\"orderStatus\\\":\\\"N\\\",\\\"payPrice\\\":0.01,\\\"postagePrice\\\":0.0,\\\"receiver\\\":\\\"kk\\\",\\\"receiverMobile\\\":\\\"15157515855\\\",\\\"skuOrderResults\\\":[{\\\"buyWay\\\":\\\"car\\\",\\\"createTime\\\":1702371757000,\\\"id\\\":2154,\\\"integral\\\":0,\\\"integralPrice\\\":0.0,\\\"isDeliverGoods\\\":\\\"N\\\",\\\"isPay\\\":\\\"N\\\",\\\"orderId\\\":2122,\\\"orderType\\\":\\\"buy\\\",\\\"payPrice\\\":0.01,\\\"periodsNumber\\\":0,\\\"skuOrderDetailResults\\\":[{\\\"categoryName\\\":\\\"单品豆\\\",\\\"count\\\":1,\\\"cover\\\":\\\"https://wjcoffee.oss-cn-hangzhou.aliyuncs.com/upload/2023/12/08/202312081127439002.png\\\",\\\"deliveryWay\\\":\\\"包邮\\\",\\\"extractSpecifications\\\":0,\\\"id\\\":2304,\\\"isDirectRefund\\\":\\\"N\\\",\\\"isFreeShipping\\\":\\\"N\\\",\\\"payPrice\\\":0.01,\\\"price\\\":0.1,\\\"skuId\\\":391,\\\"skuName\\\":\\\"分期商品1包邮\\\",\\\"skuOrderId\\\":2154,\\\"skuSalesInformationId\\\":371,\\\"supplierId\\\":3}],\\\"status\\\":\\\"waiting\\\",\\\"totalPrice\\\":0.1,\\\"type\\\":\\\"sku\\\"}]},\\\"msg\\\":\\\"SUCCESS\\\",\\\"success\\\":true}";
        String s1 = s.replaceAll("\\\\", "");
        System.out.println(s1);
    }

    @Override
    public MerchantSkuContentResult getMerchantSkuContentResult(Integer skuId, Integer merchantId, Integer cityId, String type) throws BusinessException {
        MerchantSkuContentResult merchantSkuContentResult = new MerchantSkuContentResult();
        SkuContentResult skuContentResult = skuContentDao.findSkuContentResultBySkuId(skuId);
        if (skuContentResult == null) {
            throw new BusinessException(ExceptionEnum.ERROR_1318.getCode(), ExceptionEnum.ERROR_1318.getMessage());
        }
        ValidateBusinessException.assertTrue(SkuTypeEnum.SKU.getCode().equals(skuContentResult.getSkuType()), ExceptionEnum.ERROR_1318);
        BeanUtils.copyProperties(merchantSkuContentResult, skuContentResult);
        SkuSalesInformationQuery skuSalesInformationQuery = new SkuSalesInformationQuery();
        skuSalesInformationQuery.setSkuId(skuContentResult.getSkuId());
        skuSalesInformationQuery.setType(type);
        List<SkuSalesInformation> skuSalesInformations = skuSalesInformationDao.list(skuSalesInformationQuery);
        merchantSkuContentResult.setSkuSalesInformationResult(DTOUtils.convertList(skuSalesInformations, SkuSalesInformationResult.class));
        if (cityId != null) {
            RegionalSku regionalSku = regionalSkuDao.findBySkuId(skuContentResult.getSkuId());
            if (regionalSku!=null){
                merchantSkuContentResult.setIsMembersExclusive(regionalSku.getIsMembersExclusive());
            }
            RegionalSkuSalesInformationQuery regionalSkuSalesInformationQuery = new RegionalSkuSalesInformationQuery();
            regionalSkuSalesInformationQuery.setSkuId(skuId);
            regionalSkuSalesInformationQuery.setGtRegionId(cityId);
            List<RegionalSkuSalesInformation> list = regionalSkuSalesInformationDao.list(regionalSkuSalesInformationQuery);
            if (list != null && list.size() > 0) {
                Map<Integer, RegionalSkuSalesInformation> listMap = list.stream().collect(Collectors.toMap(RegionalSkuSalesInformation::getSkuSalesInformationId, i -> i));
                List<SkuSalesInformationResult> skuSalesInformationResult = merchantSkuContentResult.getSkuSalesInformationResult();
                Iterator<SkuSalesInformationResult> iterator = skuSalesInformationResult.iterator();
                while (iterator.hasNext()) {
                    SkuSalesInformationResult salesInformationResult = iterator.next();
                    RegionalSkuSalesInformation regionalSkuSalesInformation = listMap.get(salesInformationResult.getId());
                    if (regionalSkuSalesInformation != null) {
                        salesInformationResult.setPrice(regionalSkuSalesInformation.getRegionalPrice());
                        salesInformationResult.setIntegralDeduction(regionalSkuSalesInformation.getIntegralDeduction());
                        salesInformationResult.setCycles(regionalSkuSalesInformation.getCycles());
                        salesInformationResult.setDepositDeduction(regionalSkuSalesInformation.getDepositDeduction());
                    } else {
                        iterator.remove();
                    }
                }
                merchantSkuContentResult.setSkuSalesInformationResult(skuSalesInformationResult);
            }
        }
        if (SkuSalesInformationTypeEnum.PERIODIZATION.getCode().equals(type)) {
            List<Integer> viceSkuIds = periodizationSkuDao.findViceSkuIds(skuId);
            if (viceSkuIds.size() > 0) {
                List<MerchantSkuListResult> merchantSkuListResults = skuContentDao.merchantSkuPageBySkuIdsAndPeriodization(viceSkuIds, skuId);
                if (cityId != null) {
                    RegionalSkuSalesInformationQuery regionalSkuSalesInformationQuery = new RegionalSkuSalesInformationQuery();
                    regionalSkuSalesInformationQuery.setSkuIds(viceSkuIds);
                    regionalSkuSalesInformationQuery.setHostSkuId(skuId);
                    regionalSkuSalesInformationQuery.setGtRegionId(cityId);
                    List<RegionalSkuSalesInformation> list = regionalSkuSalesInformationDao.list(regionalSkuSalesInformationQuery);
                    if (list != null && list.size() > 0) {
                        Map<Integer, RegionalSkuSalesInformation> listMap = list.stream().collect(Collectors.toMap(RegionalSkuSalesInformation::getSkuSalesInformationId, i -> i));
                        Iterator<MerchantSkuListResult> iterator = merchantSkuListResults.iterator();
                        while (iterator.hasNext()) {
                            MerchantSkuListResult merchantSkuListResult = iterator.next();
                            RegionalSkuSalesInformation regionalSkuSalesInformation = listMap.get(merchantSkuListResult.getSkuSalesInformationId());
                            if (regionalSkuSalesInformation != null) {
                                merchantSkuListResult.setDiscountPrice(regionalSkuSalesInformation.getRegionalPrice());
                                merchantSkuListResult.setDepositDeduction(regionalSkuSalesInformation.getDepositDeduction());
                                merchantSkuListResult.setCycles(regionalSkuSalesInformation.getCycles());
                                merchantSkuListResult.setDepositDeduction(regionalSkuSalesInformation.getDepositDeduction());
                            } else {
                                iterator.remove();
                            }
                        }
                        merchantSkuContentResult.setSubSkuLists(merchantSkuListResults);
                    }
                }
            }
        } else {
            {
                List<SkuSalesInformationResult> skuSalesInformationResult1 = merchantSkuContentResult.getSkuSalesInformationResult();
                if ("Y".equals(skuContentResult.getIsSpellOrder())) {
                    GtRegion gtRegion = gtRegionDao.findById(skuContentResult.getSpellOrderCityId());
                    merchantSkuContentResult.setSpellOrderCity(gtRegion.getName());
                    List<MerchantSpellOrderResult> merchantSpellOrderResults = skuOrderService.skuOrderService(skuId, skuContentResult.getSpellOrderPeople());
                    merchantSkuContentResult.setSpellOrder(merchantSpellOrderResults);
                }
                if ("Y".equals(skuContentResult.getIsIntegral())) {

                    PlatformSystemDeploy platformSystemDeploy = jfPlatformSystemDeploy();
                    Double integralPrice = null;
                    Double integralDeduction = skuContentResult.getIntegralDeduction() != null ? skuContentResult.getIntegralDeduction() : 0;
                    Map<Integer, SkuSalesInformationResult> listMap = skuSalesInformationResult1.stream().collect(Collectors.toMap(SkuSalesInformationResult::getId, i -> i));
                    Integer integral = new BigDecimal(skuSalesInformations.get(0).getPrice() + "").multiply(new BigDecimal(integralDeduction)).divide(new BigDecimal(platformSystemDeploy.getDetails()), BigDecimal.ROUND_HALF_EVEN).multiply(new BigDecimal(platformSystemDeploy.getUnit())).intValue();
                    SkuSalesInformationResult skuSalesInformationResult = listMap.get(skuSalesInformations.get(0).getId());
                    if (skuSalesInformationResult != null && skuSalesInformationResult.getIntegralDeduction() != null) {
                        integral = new BigDecimal(skuSalesInformationResult.getPrice() + "").multiply(new BigDecimal(skuSalesInformationResult.getIntegralDeduction() + "")).divide(new BigDecimal(platformSystemDeploy.getDetails()), BigDecimal.ROUND_HALF_EVEN).multiply(new BigDecimal(platformSystemDeploy.getUnit())).intValue();
                    }
                    if (merchantId==null){
                        integralPrice=0.0;
                    }else{
                        Merchant merchant = merchantDao.findById(merchantId);
                        if (merchant.getIntegral() > integral) {
                            integralPrice = new BigDecimal(integral).divide(new BigDecimal(platformSystemDeploy.getUnit()), BigDecimal.ROUND_HALF_EVEN).multiply(new BigDecimal(platformSystemDeploy.getDetails())).setScale(2).doubleValue();
                        } else if (merchant.getIntegral() > 0) {
                            integralPrice = new BigDecimal(merchant.getIntegral()).divide(new BigDecimal(platformSystemDeploy.getUnit()), BigDecimal.ROUND_HALF_EVEN).multiply(new BigDecimal(platformSystemDeploy.getDetails())).setScale(2).doubleValue();
                        }
                    }

                    merchantSkuContentResult.setIntegralPrice(integralPrice);
                }
                EnjoyBeforePaySku enjoyBeforePaySku = enjoyBeforePaySkuDao.findBySkuId(skuId);
                if (enjoyBeforePaySku != null) {
                    merchantSkuContentResult.setIsEnjoy("Y");
                }
                Supplier supplier = supplierDao.findById(skuContentResult.getSupplierId());
                if (supplier != null) {
                    merchantSkuContentResult.setSupplierName(supplier.getName());
                    merchantSkuContentResult.setBusinessName(supplier.getBusinessName());
                }
                UrbanFullReductionQuery urbanFullReductionQuery = new UrbanFullReductionQuery();
                urbanFullReductionQuery.setCityId(cityId);
                UrbanFullReduction urbanFullReductionDaoFirst = urbanFullReductionDao.findFirst(urbanFullReductionQuery);
                if (urbanFullReductionDaoFirst == null) {
                    urbanFullReductionQuery.setCityId(Integer.parseInt(nationwideId));
                    urbanFullReductionDaoFirst = urbanFullReductionDao.findFirst(urbanFullReductionQuery);
                }
                merchantSkuContentResult.setPostage(urbanFullReductionDaoFirst.getFreight());
            }
        }

        return merchantSkuContentResult;
    }


    public PlatformSystemDeploy jfPlatformSystemDeploy() throws BusinessException {
        PlatformSystemDeployQuery platformSystemDeployQuery = new PlatformSystemDeployQuery();
        platformSystemDeployQuery.setType(SkuTypeEnum.INTEGRAL.getCode());
        platformSystemDeployQuery.setStatus(IntegralOperationEnum.DEDUCTION.getCode());
        PlatformSystemDeploy platformSystemDeploy = platformSystemDeployDao.findFirst(platformSystemDeployQuery);
        ValidateBusinessException.assertNonNull(platformSystemDeploy, ExceptionEnum.ERROR_1704);
        return platformSystemDeploy;
    }


}
